﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools.cMethods
{
    public static class CommonMethods
    {
        /// <summary>
        /// 登录账号
        /// </summary>
        public static string userCode;
        /// <summary>
        /// 登录人员姓名
        /// </summary>
        public static string userName;
        /// <summary>
        /// 登录人所选账套
        /// </summary>
        public static string baseCode;
        /// <summary>
        /// 系统参数
        /// </summary>
        public static Dictionary<string, string> Parameters;
        public static string SinglePar { get; set; }
        public static string selectUserNames { get; set; }
        public static string selectUserCodes { get; set; }
        public static string userPositionValue { get; set; }
        public static string userPositionCode { get; set; }
        public static string userPositionTitle { get; set; }
        public static string positionKey { get; set; }
        public static string chooseWeight { get; set; }
        public static string singleValue { get; set; }
        public static string singleText { get; set; }
        /// <summary>
        /// 生产打印表格(后期可根据客户实际业务需求，修改打印表格)
        /// </summary>
        /// <returns></returns>
        public static DataTable createPrintTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("barCode");
            dt.Columns.Add("proName");
            dt.Columns.Add("yaGuang");
            dt.Columns.Add("proCode");
            dt.Columns.Add("spec");
            dt.Columns.Add("chengfen");
            dt.Columns.Add("maoWeight");
            dt.Columns.Add("proWeight");
            dt.Columns.Add("grade");
            dt.Columns.Add("happenDate");
            dt.Columns.Add("checkCode");
            dt.Columns.Add("checkName");
            dt.Columns.Add("Department");
            dt.Columns.Add("deptName");
            dt.Columns.Add("standard");
            dt.Columns.Add("address");
            dt.Columns.Add("phone");
            
            return dt;
        }
        public static DataTable createPrintTable(Control.ControlCollection control, Dictionary<string, string> cmPars, string barCodes)
        {
            DataTable dt = new DataTable();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            #region 容器控件数据
            foreach (Control ct in control)
            {
                string keyName = ct.Name;


                if (!dic.ContainsKey(keyName))
                {
                    if (ct is DevExpress.XtraEditors.TextEdit)
                    {
                        keyName = keyName.Replace("tb_0_", "");
                        keyName = keyName.Replace("tb_1_", "");
                        dic[keyName] = ct.Text.Trim();
                    }
                    else if (ct is ComboBox)
                    {
                        keyName = keyName.Replace("cb_0_", "");
                        keyName = keyName.Replace("cb_1_", "");
                        var cb = (ComboBox)ct;
                        string cbValue = "";
                        if (cb.SelectedValue != null && !string.IsNullOrWhiteSpace(cb.SelectedValue.ToString()))
                        {
                            cbValue = cb.SelectedValue.ToString();
                        }
                        dic[keyName] = string.Format("{0}({1})", cb.Text, cbValue);
                    }
                }
            }
            #endregion

            #region 通用参数数据
            if (cmPars != null)
            {
                foreach (var item in cmPars)
                {
                    if (!dic.ContainsKey(item.Key))
                    {
                        dic[item.Key] = item.Value;
                    }
                }
            }

            #endregion

            #region 构建数据表结构
            foreach (var item in dic)
            {
                if (!dt.Columns.Contains(item.Key))
                {
                    dt.Columns.Add(item.Key);
                }
            }
            #endregion
            if (!dt.Columns.Contains("barCode"))
            {
                dt.Columns.Add("barCode");
            }
            var arr = barCodes.Split(',');
            foreach (string s in arr)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    DataRow r = dt.NewRow();
                    r["barCode"] = s;
                    foreach (var item in dic)
                    {
                        r[item.Key] = item.Value;
                    }
                    dt.Rows.Add(r);
                }
            }
            return dt;
        }
        public static DataTable BanGunPrintTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("pCode");
            dt.Columns.Add("customName");
            dt.Columns.Add("proName");
            dt.Columns.Add("spec");
            dt.Columns.Add("banhao");
            dt.Columns.Add("zbcjName");
            dt.Columns.Add("banchang");
            dt.Columns.Add("banzhou");
            dt.Columns.Add("banzhi");
            dt.Columns.Add("gongyongban");
            return dt;
        }
        public static DataTable YangBanPrintTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("yCode");
            dt.Columns.Add("yName");
            dt.Columns.Add("weizhi");
            dt.Columns.Add("shuliang");
            dt.Columns.Add("memo");
            dt.Columns.Add("name0");
            dt.Columns.Add("name1");
            dt.Columns.Add("name2");
            dt.Columns.Add("name3");
            dt.Columns.Add("spec0");
            dt.Columns.Add("spec1");
            dt.Columns.Add("spec2");
            dt.Columns.Add("spec3");

            dt.Columns.Add("name4");
            dt.Columns.Add("name5");
            dt.Columns.Add("name6");
            dt.Columns.Add("name7");
            dt.Columns.Add("spec4");
            dt.Columns.Add("spec5");
            dt.Columns.Add("spec6");
            dt.Columns.Add("spec7");
            dt.Columns.Add("spec8");
            dt.Columns.Add("spec9");
            dt.Columns.Add("name8");
            dt.Columns.Add("name9");
            return dt;
        }
        /// <summary>
        /// 到货单打印表
        /// </summary>
        /// <returns></returns>
        public static DataTable DHDPrintTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("proCode");
            table.Columns.Add("proName");
            table.Columns.Add("spec");
            table.Columns.Add("outCompany");//供方
            table.Columns.Add("mNum");
            table.Columns.Add("cNum");
            table.Columns.Add("date");
            table.Columns.Add("barCode");
            table.Columns.Add("orderCode");
            table.Columns.Add("userName");
            return table;
        }
        /// <summary>
        /// 期初打印表格
        /// </summary>
        /// <returns></returns>
        public static DataTable QcPrintTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("proCode");
            table.Columns.Add("proName");
            table.Columns.Add("spec");
            table.Columns.Add("mishu");
            table.Columns.Add("xilie");
            table.Columns.Add("gongjin");
            table.Columns.Add("pingmi");
            table.Columns.Add("date");
            table.Columns.Add("barCode");
            table.Columns.Add("width");
            table.Columns.Add("userName");
            table.Columns.Add("customName");
            table.Columns.Add("wareHouse");//入库仓库
            table.Columns.Add("wPosition");//仓库货位
            table.Columns.Add("pici");//计划批次号
            //table.Columns.Add("cu_productIndex"); // 存货序号

            //table.Columns.Add("cu_widthRange");
            //table.Columns.Add("cu_rollLength");
            //table.Columns.Add("cu_colorCode");
            table.Columns.Add("cu_flameRetardant");
            table.Columns.Add("cu_texture");
            table.Columns.Add("proGroup");

            table.Columns.Add("cu_workGroup");

            table.Columns.Add("plCode");

            table.Columns.Add("proWeight");
            //table.Columns.Add("cu_grossWeight");

            table.Columns.Add("createtime");

            table.Columns.Add("cu_PHR");

            table.Columns.Add("cu_hardnessDegree");
            table.Columns.Add("cu_faceBottom");

            return table;
        }

        /// <summary>
        /// 只条码打印
        /// </summary>
        /// <returns></returns>
        public static DataTable onlyBarCode()
        {
            DataTable table = new DataTable();
            table.Columns.Add("barCode");
            return table;
        }

        /// <summary>
        /// 打印方法
        /// </summary>
        /// <param name="dt">打印数据源</param>
        /// <param name="templateName">模版名称</param>
        /// <param name="printName">打印机名</param>
        /// <param name="msg">错误消息</param>
        /// <returns></returns>
        public static bool DoPrint(DataTable dt, string templateName, string printName, ref string msg)
        {
            var easyPrint = new VBprinter.EasyReport();
            string currentDir = AppDomain.CurrentDomain.BaseDirectory;
            string configFile = Path.Combine(currentDir + "Template\\", templateName) + ".mb";//路径拼接
            try
            {
                if (File.Exists(configFile))
                {
                    //easyPrint.SetReportFile(@"C:\Users\Administrator\Pictures\system_drawing_color.png");
                    easyPrint.SetReportDataSource(dt);
                    easyPrint.SetReportFile(configFile);
                    easyPrint.PrintReport(false, true, false, false, printName).ToString();
                    return true;
                }
                else
                {
                    if (!Directory.Exists(Path.Combine(currentDir, "Template\\")))  //如果Folder不存在，则创建
                    {
                        Directory.CreateDirectory(Path.Combine(currentDir, "Template\\"));
                    }
                    msg = "打印模板不存在";     //未选择模版
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            
        }

        /// <summary>
        /// 打印方法
        /// </summary>
        /// <param name="dt">打印数据源</param>
        /// <param name="templateName">模版名称</param>
        /// <param name="printName">打印机名</param>
        /// <param name="msg">错误消息</param>
        /// <returns></returns>
        public static bool DoPrint_horizontal(DataTable dt, string templateName, string printName, ref string msg)
        {
            var easyPrint = new VBprinter.EasyReport();
            string currentDir = AppDomain.CurrentDomain.BaseDirectory;
            string configFile = Path.Combine(currentDir + "Template\\", templateName) + ".mb";//路径拼接

            if (File.Exists(configFile))
            {
                easyPrint.SetReportDataSource(dt);
                easyPrint.SetReportFile(configFile);
                easyPrint.PrintReport(false, true, false, false, printName).ToString();
                return true;
            }
            else
            {
                if (!Directory.Exists(Path.Combine(currentDir, "Template\\")))  //如果Folder不存在，则创建
                {
                    Directory.CreateDirectory(Path.Combine(currentDir, "Template\\"));
                }
                msg = "打印模板不存在";     //未选择模版
                return false;
            }
        }

        /// <summary>
        /// 打印模板下拉列表
        /// </summary>
        /// <param name="cmbId"></param>
        public static void loadPrintTemplte(ComboBox cmbId)
        {
            string path = Application.StartupPath;
            string strDirectory = path + "\\Template";
            DirectoryInfo TheFolder = new DirectoryInfo(strDirectory);
            List<string> list = new List<string>();
            DirectoryInfo Dir = new DirectoryInfo(strDirectory);
            FileSystemInfo[] files = Dir.GetFileSystemInfos();
            DataTable table = new DataTable();
            table.Columns.Add("cCode");
            table.Columns.Add("cName");
            foreach (FileSystemInfo f in files)
            {
                DataRow r = table.NewRow();
                r["cCode"] = f.Name;
                r["cName"] = f.Name.Split('.')[0];
                table.Rows.Add(r);
            }

            cmbId.DataSource = table;
            cmbId.ValueMember = "cCode";
            cmbId.DisplayMember = "cName";
        }
        /// <summary>
        /// 获取本机全部打印
        /// </summary>
        /// <param name="cbControl"></param>
        public static void loadPrintDevice(ComboBox cbControl)
        {
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                DataRow r = dt.NewRow();
                r["name"] = sPrint;
                r["value"] = sPrint;
                dt.Rows.Add(r);
            }
            cbControl.DataSource = dt;
            cbControl.ValueMember = "name";
            cbControl.DisplayMember = "name";
            cbControl.SelectedValue = sDefault;
        }

        /// <summary>
        /// 获取sys_dictionaries_info 信息
        /// </summary>
        public static void loadDictionaries(string types, ComboBox cbControl)
        {
            var sql_template = "select * from sys_dictionaries_info where status = 1 and types = '{0}'; ";
            var sql = string.Format(sql_template, types);

            DBHelper db = new DBHelper();
            var dt = db.getData(sql);

            cbControl.ValueMember = "code";
            cbControl.DisplayMember = "name";
            cbControl.DataSource = dt;

        }

        /// <summary>
        /// 将计划信息赋值到打印表单
        /// </summary>
        /// <param name="pDatas">计划数据字符串(json格式)</param>
        /// <param name="control">控件容器</param>
        public static void PlanInfoSetForm(Dictionary<string, string> pDatas, Control.ControlCollection control, bool onlyRead)
        {
            var json = JsonConvert.DeserializeObject<JObject>(pDatas["pars"]);
            foreach (Control ct in control)
            {
                if (ct is DevExpress.XtraEditors.TextEdit)
                {
                    string cName = ct.Name.Replace("tb_1_", "");
                    cName = cName.Replace("tb_0_", "");
                    foreach (var obj in json as JObject)
                    {
                        if (json.Property(cName) != null && !string.IsNullOrWhiteSpace(json[cName].ToString()))
                        {
                            ct.Text = json[cName].ToString();
                            if (onlyRead)
                            {
                                var tb = (DevExpress.XtraEditors.TextEdit)ct;
                                tb.Properties.ReadOnly = true;
                            }
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 获取表单数据(含通用数据)
        /// </summary>
        /// <param name="control">容器id</param>
        /// <param name="cmPars">通用参数集合</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetFormData(Control.ControlCollection control, Dictionary<string, string> cmPars)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            try
            {
                foreach (Control ct in control)
                {
                    if (ct is DevExpress.XtraEditors.TextEdit)
                    {
                        if (ct.Name.Contains("tb_1_"))
                        {
                            string cName = ct.Name.Replace("tb_1_", "");
                            dic[cName] = ct.Text;
                        }
                    }
                    else if (ct is ComboBox)
                    {
                        var cb = (ComboBox)ct;
                        if (cb.Name.Contains("cb_1_"))
                        {
                            string cName = ct.Name.Replace("cb_1_", "");
                            if (cb.SelectedValue != null)
                            {
                                dic[cName] = cb.SelectedValue.ToString();
                            }
                        }

                    }
                }
                if (cmPars != null)
                {
                    foreach (var item in cmPars)
                    {
                        if (!dic.ContainsKey(item.Key))
                        {
                            dic[item.Key] = item.Value;
                        }
                    }
                }

                return dic;
            }
            catch (Exception ex)
            {

            }
            return null;
        }

        #region "getobject filled object with property reconized"

        public static List<T> ConvertTo<T>(DataTable datatable) where T : new()
        {
            List<T> Temp = new List<T>();
            try
            {
                List<string> columnsNames = new List<string>();
                foreach (DataColumn DataColumn in datatable.Columns)
                    columnsNames.Add(DataColumn.ColumnName);
                Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
                return Temp;
            }
            catch
            {
                return Temp;
            }

        }
        public static T getObject<T>(DataRow row, List<string> columnsName) where T : new()
        {
            T obj = new T();
            try
            {
                string columnname = "";
                string value = "";
                PropertyInfo[] Properties;
                Properties = typeof(T).GetProperties();
                foreach (PropertyInfo objProperty in Properties)
                {
                    columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
                    if (!string.IsNullOrEmpty(columnname))
                    {
                        value = row[columnname].ToString();
                        if (!string.IsNullOrEmpty(value))
                        {
                            if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                            {
                                value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                            }
                            else
                            {
                                value = row[columnname].ToString().Replace("%", "");
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                            }
                        }
                    }
                }
                return obj;
            }
            catch
            {
                return obj;
            }
        }

        #endregion

        #region "New DataTable"
        public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {
            DataTable newDataTable = new DataTable();
            Type impliedType = typeof(T);
            PropertyInfo[] _propInfo = impliedType.GetProperties();
            foreach (PropertyInfo pi in _propInfo)
                newDataTable.Columns.Add(pi.Name, pi.PropertyType);

            foreach (T item in collection)
            {
                DataRow newDataRow = newDataTable.NewRow();
                newDataRow.BeginEdit();
                foreach (PropertyInfo pi in _propInfo)
                    newDataRow[pi.Name] = pi.GetValue(item, null);
                newDataRow.EndEdit();
                newDataTable.Rows.Add(newDataRow);
            }
            return newDataTable;
        }
        #endregion

        public static string GetDateStr(string dateDelimiter = "-")
        {
            var dateStr = "yyyy" + dateDelimiter + "MM" + dateDelimiter + "dd";
            return DateTime.Now.ToString(dateStr);
        }

        public static string GetTimeStr(string dateDelimiter = "-")
        {
            var timeStr = "yyyy" + dateDelimiter + "MM" + dateDelimiter + "dd " + "HH:mm:ss";
            return DateTime.Now.ToString(timeStr);
        }
        public static string GetYear()
        {
            return DateTime.Now.ToString("yyyy");
        }

        public static string SafetyGetRowString(DataRow row, string key)
        {
            if (!row.IsNull(key))
            {
                return row[key].ToString();
            }
            return "";
        }
        public static int SafetyGetRowInt(DataRow row, string key)
        {
            if (!row.IsNull(key))
            {
                var val = 0;
                int.TryParse(row[key].ToString(), out val);
                return val;
            }
            return 0;
        }
        public static decimal SafetyGetRowDecimal(DataRow row, string key)
        {
            if (!row.IsNull(key))
            {
                var val = 0.0m;
                decimal.TryParse(row[key].ToString(), out val);
                return val;
            }
            return 0.0m;
        }
    }
}
